package cn.kgc.ssm.intcepters;

import cn.hutool.json.JSONUtil;
import cn.kgc.ssm.response.ResponseResult;
import cn.kgc.ssm.response.ResponseStatus;
import com.alibaba.druid.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2024/11/23
 * @description
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        String authentication = (String) session.getAttribute("authentication");
        if (StringUtils.isEmpty(authentication)){   // 没有认证
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            ResponseResult msg = ResponseResult.fail().code(ResponseStatus.NOT_LOGIN).msg(ResponseStatus.NOT_LOGIN.getMessage());
            writer.write(JSONUtil.toJsonStr(msg));
            writer.close();

            return  false;
        }
        return  true;
    }
}
